<?php namespace App\Services;

use Auth;
use App\Exceptions\ValidateParameterException;
use Carbon\Carbon;
use Cache;
use App\Facades\Infra\CustomerManager;
use App\Utils\PhoneMessage;
use App\Exceptions\SendPhoneCodeException;
use Hash;

class CustomerService{
	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-14
	 * @desc     账号密码登录
	 * @param    [type]
	 * @return   [type]
	 */
	public function login($data){

		if (!Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
            throw new ValidateParameterException('账号或者密码不正确');
        }
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-14
	 * @desc     验证码登录
	 * @param    [type]
	 * @return   [type]
	 */
	public function codeLogin($data){
		if(!Cache::has('login'.$data['phone'])){
			throw new ValidateParameterException('验证码不存在或者已经过期');
		}
		else{
			if($data['code'] != Cache::get('login'.$data['phone'])){
				throw new ValidateParameterException('验证码错误');
			}
			$customer = CustomerManager::getCustomers($conditions = ['phone' => $data['phone']],$first = false);

			Auth::login($customer);
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     获取验证码
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function getCode($data){
		try {
			$code = rand(100000, 999999);

			$expiresAt = Carbon::now()->addMinutes(10);

			Cache::put('login'.$data['phone'],$code, $expiresAt);

			$this->sendCode($data['phone'],config('global.phoneMsg.login_model'),$code);

			return ['code' => $code];

		} catch (Exception $e) {
			throw new SendPhoneCodeException($e->getMessage());
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     获取验证码（忘记密码）
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function getForgetCode($data){
		try {
			$code = rand(100000, 999999);

			$expiresAt = Carbon::now()->addMinutes(10);

			Cache::put('update'.$data['phone'],$code, $expiresAt);

			$this->sendCode($data['phone'],config('global.phoneMsg.forget_password_model'),$code);

			return ['code' => $code];

		} catch (Exception $e) {
			throw new SendPhoneCodeException($e->getMessage());
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     获取验证码（注册）
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function getRegisterCode($data){
		try {
			$code = rand(100000, 999999);

			$expiresAt = Carbon::now()->addMinutes(10);

			Cache::put('register'.$data['phone'],$code, $expiresAt);

			$this->sendCode($data['phone'],config('global.phoneMsg.register_model'),$code);

			return ['code' => $code];

		} catch (Exception $e) {
			throw new SendPhoneCodeException($e->getMessage());
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     修改密码（忘记密码）
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function forgetPwd($data){
		if(!Cache::has('update'.$data['phone'])){
			throw new ValidateParameterException('验证码不存在或者已经过期');
		}
		else{
			if($data['code'] != Cache::get('update'.$data['phone'])){
				throw new ValidateParameterException('验证码错误');
			}
			$updateData = [
				'password' => bcrypt($data['newPassword'])
			];

			$customer = CustomerManager::getCustomers($conditions = ['phone' => $data['phone']],$first = false);

			return CustomerManager::updateCustomer($customer,$updateData);
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     注册
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function register($data){
		if(!Cache::has('register'.$data['phone'])){
			throw new ValidateParameterException('验证码不存在或者已经过期');
		}
		else{
			if($data['code'] != Cache::get('register'.$data['phone'])){
				throw new ValidateParameterException('验证码错误');
			}
			$createData = [
				'phone' => $data['phone'],
				'password' => bcrypt($data['password'])
			];

			return CustomerManager::createCustomer($createData);
		}
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     修改密码
	 * @param    [type]     $data [description]
	 * @return   [type]           [description]
	 */
	public function updatePwd($data){

		// dd(Hash::check($data['password'],Auth::user()->getAuthPassword()));

		if (!Hash::check($data['password'],Auth::user()->getAuthPassword())) {
			throw new ValidateParameterException("原密码不正确");
		}
		$updateData = [
			'password' => $data['newPassword']
		];

		CustomerManager::updateCustomer(Auth::user(),$updateData);

		Auth::logout();
	}

	/**
	 * @Author   Leikes
	 * @DateTime 2018-05-15
	 * @desc     发送验证码
	 * @param    [type]     $code [description]
	 * @return   [type]           [description]
	 */
	private function sendCode($phone,$modelId,$code){

		$phoneMsg = new PhoneMessage($phone,$modelId,$code);

		$phoneMsg->sendPhoneMsg();
	}
}